package com.api;

import com.api.entity.CncData;
import com.api.entity.NcFile;

import com.dto.cnc.ToolsDTO;
import com.dto.config.IniDTO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@CrossOrigin
public class WebController {


    /**
     *
     * http://localhost:6969/checkFile/?filePath=%22s%22&fileMD5=%22ss%22
     * @param cncData
     * @param modelMap
     * @return
     */
    @SneakyThrows
    @RequestMapping(value = "/cncData",method = RequestMethod.GET)
//    @ResponseStatus(code=HttpStatus.INTERNAL_SERVER_ERROR,reason="server error")

//    ResponseEntity<String>  不仅可以返回json结果，还可以定义返回的HttpHeaders和HttpStatus
    public  ResponseEntity<Map<String,Object>> getServerStatus(
            @ModelAttribute("cncData") CncData cncData, ModelMap modelMap,
            HttpServletResponse httpResponse
    ) {

//        HttpStatus httpStatus = ;
//        if (httpStatus.is2xxSuccessful()){
//            httpState = 200;
//        }
//        if (httpStatus.is5xxServerError()){
//            httpState = 500;
//        }
//        if (httpStatus.is1xxInformational()){
//            httpState = 100;
//        }
//        if (httpStatus.is4xxClientError()){
//            httpState = 400;
//        }
//        if (httpStatus.is3xxRedirection()){
//            httpState = 300;
//        }
//        if (httpStatus.isError()){
//            httpState = 0;
//        }


        modelMap.addAttribute("alarm", cncData.getAlarm());
        modelMap.addAttribute("state", cncData.getNcstate());
        modelMap.addAttribute("proctimestart", cncData.getProctimestart());
//        modelMap.addAttribute("now-tools", ToolsDTO.getToolName());


        /*json*/
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("alarm", cncData.getAlarm());
        map.put("state", cncData.getNcstate());
        map.put("proctimestart", cncData.getProctimestart());
        map.put("status", httpResponse.getStatus());
        map.put("now-tools", ToolsDTO.getToolName());//当前使用刀具



        return new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK);

    }


    /**
     * http://localhost:8000/checkFile/?filePath=/a/b/c.nc&fileMD5=%22ss%22
     * http://localhost:8000/checkFile/?filePath=%22s%22&fileMD5=%22ss%22
     * @param ncFile
     * @param modelMap
     * @return
     */
    @SneakyThrows
    @RequestMapping(value = "/checkFile",method = RequestMethod.GET)
//    @ResponseStatus(code=HttpStatus.INTERNAL_SERVER_ERROR,reason="server error")

//    ResponseEntity<String>  不仅可以返回json结果，还可以定义返回的HttpHeaders和HttpStatus
    public  ResponseEntity<Map<String,Object>> getServerStatus(
            @ModelAttribute("fileCheck") NcFile ncFile, ModelMap modelMap,
            HttpServletResponse httpResponse
    ) {
        String filePath;
        boolean fileResult ;
        int httpState;
        String oldMD5;
        String fileMD5 = "";
//        HttpStatus httpStatus = ;
//        if (httpStatus.is2xxSuccessful()){
//            httpState = 200;
//        }
//        if (httpStatus.is5xxServerError()){
//            httpState = 500;
//        }
//        if (httpStatus.is1xxInformational()){
//            httpState = 100;
//        }
//        if (httpStatus.is4xxClientError()){
//            httpState = 400;
//        }
//        if (httpStatus.is3xxRedirection()){
//            httpState = 300;
//        }
//        if (httpStatus.isError()){
//            httpState = 0;
//        }


        modelMap.addAttribute("filePath", ncFile.getFilePath());
        modelMap.addAttribute("fileMD5", ncFile.getFileMD5());
        modelMap.addAttribute("fileChekResult", ncFile.getFileChekResult());
//        modelMap.addAttribute("fileChekResult",ncFile.getFileChekResult());

        oldMD5 = ncFile.getFileMD5();
        filePath = IniDTO.getSftp_path() + ncFile.getFilePath();
        filePath = filePath.replace("\\", "/");
        filePath = filePath.replace("//", "/");
//        filePath = filePath.trim();
        /*C:\Users\jasonsang\Desktop\sftp-v2\src\main\resources\config.ini*/
        String newFilePath = filePath.replace(":/", ":\\");
        newFilePath = newFilePath.replace("/", "\\");
        System.out.println("newFilePath:" + newFilePath);


//            //建立连接
//            Connection con = new Connection(IniDTO.getHost(), Integer.parseInt(IniDTO.getPort()));
////连接
//            con.connect();
////远程服务器的用户名密码
////        boolean isAuthed =
//            con.authenticateWithPassword(IniDTO.getUsername(), IniDTO.getPassword());
////建立SCP客户端
//            SCPClient scpClient = con.createSCPClient();
////获取文件内容
//            ByteArrayOutputStream baos = new ByteArrayOutputStream();
//
////            String tt = "";
////            scpClient.get(tt, baos);
////            System.out.println(tt+"---------------");
//            con.close();
//                log.info("找到文件:"+newFilePath);
//
////
//            if (baos.size()>0){
//                log.info("文件大小:"+baos.size());

//                //Use MD5 algorithm
//                MessageDigest md5Digest = MessageDigest.getInstance("MD5");
//                fileMD5 = getFileChecksum(md5Digest,in);

        try {
            if (!new File(newFilePath).exists()){
                fileResult = false;
            } else {
                FileInputStream in = new FileInputStream(newFilePath);

//            FileChannel ch = in.getChannel();
//            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
//            messageDigest.reset();

//            ByteBuffer buffer = ByteBuffer.allocate(65536);
//
//            while(ch.read(buffer)>0) {
//                buffer.flip();
////                messageDigest.update(buffer);
////                fileMD5 = getFileChecksum(messageDigest, new File(newFilePath));
//                buffer.clear();
//            }

                fileMD5 =  org.apache.commons.codec.digest.DigestUtils.md5Hex(in);

                in.close();
            }
        } catch (IOException e) {
            // e.printStackTrace();
            log.error("文件请求失败"+e);
            fileResult = false;

        }


//            FileOutputStream outputStream = new FileOutputStream(filePath);
//            FileChannel channel = outputStream.getChannel();
//            ByteBuffer buffer = ByteBuffer.allocate(1024);
//            buffer.flip();     //此处必须要调用buffer的flip方法
////        channel.write(buffer);
////        channel.read(buffer);
//            channel.close();
//            outputStream.close();

        if (oldMD5.equals(fileMD5)){
            log.info("md5检测通过:"+fileMD5);
            fileResult = true;
        } else {
            log.error("md5错误:" + fileMD5);
            fileResult = false;
        }


        /*json*/
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("filePath", filePath);
        map.put("oldFileMD5", ncFile.getFileMD5());
        map.put("newFileMD5", fileMD5);
        map.put("fileResult", fileResult);
        map.put("status", httpResponse.getStatus());

        fileMD5 = "";
        return new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK);

    }

}